﻿Imports System.ServiceModel.DomainServices.Client
Imports LullabyFullDeCaixa.Web
Imports System.Collections.ObjectModel

Partial Public Class DetallGestioDocuments
    Inherits ChildWindow

#Region "Crear i Destruir"
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub Child_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, True)
    End Sub

    Private Sub DetallGestioHostals_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        If RiaContext.Current.Authentication.User.Identity.IsAuthenticated = True Then
            Me.Activity.IsActive = True

            AddHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
            Contexte.LoadHostals()
            AddHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
            Contexte.LoadUsuaris()

            Me.grdDocuments.ItemsSource = DadesBuscador
        End If
    End Sub
#End Region

#Region "Guardar i Cancelar"
    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        EliminarObjectErrors()

        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            If ValidarDades() Then
                LullabyFullDeCaixa.Contexte.DomainContext.SubmitChanges(AddressOf DomainContext_SubmittedChanges, Nothing)
                Activity.IsActive = True
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Function ValidarDades() As Boolean
        Dim Resultat As Boolean = True

        Return Resultat
    End Function

    Private Sub DomainContext_SubmittedChanges(ByVal s As SubmitOperation)
        Activity.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.ErrorGuardantDades)
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            LullabyFullDeCaixa.Contexte.DomainContext.RejectChanges()
        End If

        Me.DialogResult = False
    End Sub

    Public Sub EliminarObjectErrors()
        Dim i As Long

        i = 0
        While i < Validacio.Errors.Count
            If Validacio.Errors(i).ItemType = ValidationSummaryItemType.ObjectError Then
                Validacio.Errors.RemoveAt(i)
            Else
                i = i + 1
            End If
        End While
    End Sub
#End Region

#Region "Carregar Dades"
    Private _HostalsCarregats As Boolean = False
    Private _UsuarisCarregats As Boolean = False

    Public Sub HostalsCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
        _HostalsCarregats = True

        If _HostalsCarregats And _UsuarisCarregats Then
            Me.Activity.IsActive = False
            OmpleDadesBuscador()
        End If
    End Sub

    Public Sub UsuarisCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
        _UsuarisCarregats = True

        If _HostalsCarregats And _UsuarisCarregats Then
            Me.Activity.IsActive = False
            OmpleDadesBuscador()
        End If
    End Sub

#End Region

#Region "Buscador"

    Private DadesBuscador As ObservableCollection(Of Document) = New ObservableCollection(Of Document)

    Private Sub Buscador_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        BuscaNeteges(True)
    End Sub

    Private Sub OmpleDadesBuscador()
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Dim LListaHostals As List(Of Hostal) = Contexte.Hostals.ToList
            LListaHostals.Insert(0, New Hostal() With {.Id = -1, .Nom = ""})
            Me.cboHostals.ItemsSource = LListaHostals
        Else
            Me.cboHostals.ItemsSource = Contexte.HostalsPerUsuariActual
        End If

        Me.cboHostals.SelectedItem = cboHostals.Items(0)

        BuscaNeteges(True)
    End Sub

    Private Sub BuscaNeteges(MostrarBarraProgrés As Boolean)
        Me.Activity.IsActive = MostrarBarraProgrés

        Dim DataInicial As Date?
        Dim DataFinal As Date?

        DataInicial = CDate("01/" & Now.Date.Month & "/" & Now.Date.Year - 1)
        If DataInicial.HasValue Then DataInicial = Date.SpecifyKind(DataInicial.Value.Date, DateTimeKind.Utc)

        DataFinal = CDate("01/" & Now.Date.Month & "/" & Now.Date.Year + 1)
        If DataFinal.HasValue Then DataFinal = Date.SpecifyKind(DataFinal.Value.Date, DateTimeKind.Utc)

        LullabyFullDeCaixa.Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetDocumentsPerHostalIDatesQuery(DirectCast(Me.cboHostals.SelectedItem, Hostal).Id, DataInicial, DataFinal), _
           New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.Document))(AddressOf DocumentsLoaded), _
           Nothing)
    End Sub

    Private Sub DocumentsLoaded(ByVal Documents As LoadOperation(Of LullabyFullDeCaixa.Web.Document))
        'Un cop carregat ho guardem en una llista
        Me.Activity.IsActive = False

        'Afegim els nous
        For Each Document As Document In (From D As Document In Documents.Entities Order By D.DataInicial Descending, D.IdHostal).ToList()
            If Not DadesBuscador.Contains(Document) Then DadesBuscador.Insert(0, Document)
        Next

        'Traiem els vells
        Dim DocumentsATreure As List(Of Document) = New List(Of Document)
        For Each Document As Document In DadesBuscador
            If Not Documents.Entities.Contains(Document) Then DocumentsATreure.Add(Document)
        Next

        For Each Document As Document In DocumentsATreure
            DadesBuscador.Remove(Document)
        Next

    End Sub
#End Region

#Region "Boto Eliminar i afegir"

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim Document As Document = DirectCast(grdDocuments.SelectedItem, Document)

        LullabyFullDeCaixa.Contexte.DomainContext.Documents.Remove(Document)

        DadesBuscador.Remove(Document)
    End Sub

    Private Sub btnAfegir_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim nouDocument As New LullabyFullDeCaixa.Web.Document() With {.IdUsuari = Contexte.UsuariActual.Id}
        Contexte.DomainContext.Documents.Add(nouDocument)


        Dim Child As DocumentAltaModificacio = New DocumentAltaModificacio(DocumentAltaModificacio.EnumMode.ModeAlta, nouDocument)
        AddHandler Child.Closed, AddressOf Child_Tancat

        Child.Show()
    End Sub

    Private Sub btnEditar_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim Document As Document = grdDocuments.SelectedItem

        Dim Child As DocumentAltaModificacio = New DocumentAltaModificacio(DocumentAltaModificacio.EnumMode.ModeModificacio, Document)
        Child.Show()
    End Sub

    Private Sub btnDescarregar_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim Document As Document = grdDocuments.SelectedItem

        Dim uri As String = "/Documents/" + Document.Id.ToString() + "_" + Document.FileName
        System.Windows.Browser.HtmlPage.Window.Eval("window.open('" & uri & "', '_blank')")
    End Sub

    Private Sub Child_Tancat(Sender As Object, e As System.EventArgs)
        Dim Child As DocumentAltaModificacio = DirectCast(Sender, DocumentAltaModificacio)
        RemoveHandler Child.Closed, AddressOf Child_Closed

        If Child.DialogResult And Child.Mode = DocumentAltaModificacio.EnumMode.ModeAlta Then
            DadesBuscador.Insert(0, Child.Document)
            grdDocuments.SelectedItem = Child.Document
        End If
    End Sub
#End Region

    Private Sub grdDocuments_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdDocuments.SelectionChanged
        If e.AddedItems.Count = 0 Then
            Me.gridDetall.Visibility = Windows.Visibility.Collapsed
            Me.btnEliminar.IsEnabled = False
            Me.btnEditar.IsEnabled = False
            Me.btnDescarregar.IsEnabled = False
        Else
            Dim Document As Document = DirectCast(e.AddedItems(0), Document)

            Me.gridDetall.Visibility = Windows.Visibility.Visible
            Me.btnEliminar.IsEnabled = True
            Me.btnEditar.IsEnabled = True
            Me.btnDescarregar.IsEnabled = True
        End If
    End Sub

    Private Sub Scroll_SizeChanged(ByVal sender As System.Object, ByVal e As System.Windows.SizeChangedEventArgs)
        Me.Components.MaxHeight = Math.Max(Me.Scroll.ViewportHeight, Me.Components.MinHeight)
        Me.Components.MaxWidth = Math.Max(Me.Scroll.ViewportWidth, Me.Components.MinWidth)
    End Sub

End Class

